/* 
 * A664p7_ethernet.c -- Implements ethernet header manipulation functions
 *
 */


#include "A664p7_internal.h"
#include "stdio.h"
#include "string.h"
#include "def.h"

/*
 * eh_to_net:  Swaps bytes for host->net conversion of Ethernet header
 * INPUTS: h -- A pointer to the ETHERNET_HEADER structure to be modified 
 * RETURNS: A664P7_FAIL on failure, A664P7_SUCC on success
 */
int eh_to_net(ETHERNET_HEADER *h)
{
	if(!h)
		return A664P7_FAIL;

	h->type = htons(h->type);
	return A664P7_SUCC;
}

/*
 * eh_from_net:  Swaps bytes for net->host conversion of Ethernet header
 * INPUTS: h -- A pointer to the ETHERNET_HEADER structure to be modified 
 * RETURNS: A664P7_FAIL on failure, A664P7_SUCC on success
 */
int eh_from_net(ETHERNET_HEADER *h)
{
	if(!h)
		return A664P7_FAIL;

	h->type = ntohs(h->type);
	return A664P7_SUCC;
}

/*
 * initialize_ethernet_header:  Sets the constants in an ETHERNET_HEADER structure &
 *                              converts it to network order
 * INPUTS: h -- A pointer to the ETHERNET_HEADER structure to be modified 
 * RETURNS: A664P7_FAIL on failure, A664P7_SUCC on success
 */
int initialize_ethernet_header(ETHERNET_HEADER *h)
{
	if(!h)
		return A664P7_FAIL;

	h->type = ETH_TYPE_IP;

	eh_to_net(h);
	return A664P7_SUCC;
}

/*
 * populate_ethernet_header:  Sets the non-constant values in an ethernet header
 * INPUTS: h          -- A pointer to the ETHERNET_HEADER structure to be modified
 *         source_mac -- A pointer to an array containing the source MAC address to be copied into the header
 *						 Passing NULL will cause source_mac to be filled with zeros.
 *		   dest_mac   -- A pointer to an array containing the destination MAC address to be copied into the header
 *						 Passing NULL will cause source_mac to be filled with zeros.
 *         type       -- The value to be inserted into the header's "type" field
 * RETURNS: A664P7_FAIL on failure, A664P7_SUCC on success
 */
int populate_ethernet_header(ETHERNET_HEADER *h, unsigned char *source_mac, unsigned char *dest_mac, unsigned short int type)
{
	if(!h)
		return A664P7_FAIL;

	if(dest_mac)
		memcpy(h->dest, dest_mac, sizeof(unsigned char)*6);
	else
		memcpy(h->dest, "000000", sizeof(unsigned char)*6);

	if(source_mac)
		memcpy(h->source, source_mac, sizeof(unsigned char)*6);
	else
		memcpy(h->source, "000000", sizeof(unsigned char)*6);
	h->type = type;

	return A664P7_SUCC;
}
